package online.yysh.charging.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import online.yysh.charging.bean.Login;
import online.yysh.charging.bean.request.LoginRequest;
import online.yysh.charging.bean.response.LoginResponse;
import online.yysh.charging.livedata.UserManager;
import online.yysh.charging.livedata.WXLoginManager;
import online.yysh.charging.utils.Constant;
import online.yysh.charging.utils.HttpUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private final String TAG = getClass().getSimpleName();
    private IWXAPI api;
    private BaseResp resp = null;
    // 获取第一步的code后，请求以下链接获取access_token
    private String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    // 获取用户个人信息
    private String GetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, WXConstant.WX_APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
//        finish();
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) resp).code;

                /*
                 * 将你前面得到的AppID、AppSecret、code，拼接成URL 获取access_token等等的信息(微信)
                 */
                String get_access_token = getCodeRequest(code);
                Log.e(TAG, "get_access_token:" + get_access_token);
                WXHttpUtil.sendToken(get_access_token, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Log.e(TAG, "sendToken:" + result);
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(result);
                            String openid = jsonObject.getString("openid").trim();
                            String access_token = jsonObject.getString("access_token").trim();
                            getUserInfo(getUserInfo(access_token, openid));

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                finish();
                break;
        }
    }

    /**
     * 通过拼接的用户信息url获取用户信息
     *
     * @param userInfoUrl
     */
    private void getUserInfo(String userInfoUrl) {
        WXHttpUtil.getWXMessage(userInfoUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "getUserInfo:" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    //微信用户唯一标识
                    final String unionId = jsonObject.getString("unionid");
                    //头像
                    final String headImgUrl = jsonObject.getString("headimgurl");
                    final String nickName = jsonObject.getString("nickname");
                    String oid = jsonObject.getString("openid");

                    final WXLogin login = new WXLogin(unionId, oid, headImgUrl, nickName);
                    getSharedPreferences(Constant.SP_NAME, MODE_PRIVATE)
                            .edit()
                            .putString(Constant.SP_KEY_NICK_NAME, login.getNickName())
                            .putString(Constant.SP_KEY_HEAD_IMAGE_URL, login.getHeadImgUrl())
                            .commit();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            WXLoginManager.getInstance().getLiveData().setValue(login);
                        }
                    });
                    //登陆
                    login(oid, unionId);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //登陆
    private void login(String oid, String openId) {
        HttpUtil.getInstance().login(new LoginRequest(openId, oid), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "login: " + result);
                Gson gson = new Gson();
                LoginResponse loginResponse = gson.fromJson(result, LoginResponse.class);
                if ("ok".equals(loginResponse.getStatus())) {
                    final Login login = loginResponse.getData();

                    getSharedPreferences(Constant.SP_NAME, MODE_PRIVATE)
                            .edit()
                            .putString(Constant.SP_KEY_OPENID, login.getOpenid())
                            .commit();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            UserManager.getInstance().getLiveData().setValue(login);
                        }
                    });
                    finish();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WXEntryActivity.this, "登录失败，点击头像重新登陆", Toast.LENGTH_SHORT).show();
                        }
                    });
                    finish();
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    /**
     * 获取access_token的URL（微信）
     *
     * @param code 授权时，微信回调给的
     * @return URL
     */
    private String getCodeRequest(String code) {
        String result = null;
        GetCodeRequest = GetCodeRequest.replace("APPID",
                urlEnodeUTF8(WXConstant.WX_APP_ID));
        GetCodeRequest = GetCodeRequest.replace("SECRET",
                urlEnodeUTF8(WXConstant.WX_APP_SECRET));
        GetCodeRequest = GetCodeRequest.replace("CODE", urlEnodeUTF8(code));
        result = GetCodeRequest;
        Log.e(TAG, "getCodeRequest:" + result);
        return result;
    }

    /**
     * 获取用户个人信息的URL（微信）
     *
     * @param access_token 获取access_token时给的
     * @param openid       获取access_token时给的
     * @return URL
     */
    private String getUserInfo(String access_token, String openid) {
        String result = null;
        GetUserInfo = GetUserInfo.replace("ACCESS_TOKEN",
                urlEnodeUTF8(access_token));
        GetUserInfo = GetUserInfo.replace("OPENID", urlEnodeUTF8(openid));
        result = GetUserInfo;
        return result;
    }

    private String urlEnodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
